// pages/addStorage/addStorage.js
import { shareOptions } from '../../utils/access';
import api from '../../config/api';
import request from '../../utils/request';
import { uploadAliyun } from '../../utils/UploadAliyun';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 是否是修改页面
    isEdit: false,
    // 是否是空间页面
    isSpace: false,
    // 图片推荐数据
    dataList: [],
    // 默认图片地址
    defaultPicPath: null,
    // 图片地址
    picPath: null,
    // 录音地址
    voicePath: null,
    // 录音时长
    voiceTime: 0,
    // 名称
    name: null,
    // 备注
    remark: null,
    // 空间id
    spaceId: null,
    // 空间选中项
    spaceSelect: null,
    // 空间列表
    spaceList: [],
    // 录音是否在播放中
    playing: false,
    // 是否含有子物品元素
    hasChild: false,
  },

  // 页面id
  id: null,
  // 请求loading
  loading: false,
  // 音频播放
  audioPlayer: wx.createInnerAudioContext(),


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const isEdit = !!options?.id
    const isSpace = !!+options?.isSpace

    this.setData({
      title: (isEdit ? '修改' : '添加')
        + (isSpace ? '空间' : '容器'),
    })

    this.id = options?.id
    this.setData({
      isEdit,
      isSpace,
      spaceId: +options?.spaceId
    }, () => {
      if (!isSpace) {
        this.getSpaceList()
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.modal = this.selectComponent('#modal')
    this.recommend = this.selectComponent('#recommend')
    this.removeModal = this.selectComponent('#removeModal')
    this.record = this.selectComponent('#record')
    // 播放录音&停止录音监听
    this.audioPlayer.onPlay(() => {
      this.setData({
        playing: true
      })
    })
    this.audioPlayer.onStop(() => {
      this.setData({
        playing: false
      })
    })
    this.audioPlayer.onEnded(() => {
      this.setData({
        playing: false
      })
    })
    if (this.data.isEdit) {
      this.recommend.clearSelect()
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.loading = false
    if (this.id) {
      this.getData()
    }
    this.getPicList()
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    const { playing } = this.data
    if (playing) {
      this.audioPlayer.stop()
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    const { playing } = this.data
    if (playing) {
      this.audioPlayer.stop()
    }
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  // 获取空间列表数据
  async getPicList() {
    const { isSpace } = this.data

    const res = await request.get(
      api.spaceContainerPics,
      { recommendType: isSpace ? 1 : 2 }
    )
    
    this.setData({
      dataList: (res?.data || []).map(item => ({
        name: item.recommendName,
        picUrls: item.picUrls
      })),
      defaultPicPath: res?.data?.[0]?.picUrls?.[0]
    })
  },
  // 获取空间列表数据
  async getSpaceList() {
    const res = await request.get(api.spaceList)
    const spaceList = res?.data?.spaceData || []
    let spaceSelect = null
    const { spaceId } = this.data

    if (spaceId) {
      spaceSelect = spaceList.find(f => f.id === spaceId)
    }

    this.setData({
      spaceList,
      spaceSelect,
    })
  },
  // 获取详情数据
  async getData() {
    const { isSpace } = this.data
    const res = await request.get(
      `${isSpace ? api.spaceDetail : api.containerDetail}/${this.id}`,
    )
    const {
      spaceName,
      containerName,
      picUrl,
      remarkVoice,
      remarkText,
      voiceLength,
      spaceId,
      itemNum,
      containerNum
    } = res?.data || {}
    this.audioPlayer.src = remarkVoice
    this.setData({
      name: spaceName || containerName,
      picPath: picUrl,
      voicePath: remarkVoice,
      voiceTime: voiceLength,
      remark: remarkText,
      spaceId,
      hasChild: isSpace ? !!containerNum : !!itemNum
    })
  },
  // 图片推荐变化
  async picChange(e) {
    const { pic } = e?.detail || {}
    this.setData({
      picPath: pic
    })
  },
  // 显示录音
  showRecord() {
    this.setData({
      voicePath: null
    })
    this.modal.hide()
    this.record.show()
  },
  // 录音提交
  recordSubmit(e) {
    uploadAliyun(
      e?.detail.tempFilePath,
      (voicePath) => {
        if (voicePath) {
          this.setData({
            voicePath,
            voiceTime: (e?.detail?.duration / 1000).toFixed(0)
          })
          this.audioPlayer.src = voicePath
        }
      },
      { directory: 'kejian-voice/' }
    )
  },
  // 播放录音
  play() {
    const { playing } = this.data
    if (playing) {
      this.audioPlayer.stop()
    } else {
      this.audioPlayer.play()
    }
  },
  // 重新录制
  reRecord() {
    this.modal.show()
  },
  // 显示拍照sheet
  showPhoto() {
    wx.chooseImage({
      count: 1,
      success: (img) => {
        const [imgData] = img?.tempFiles || [{}]
        console.log(imgData);
        if (!imgData) {
          wx.showToast({
            icon: 'none',
            title: '没有获取到图片数据',
          })
          return
        }
        if (['jpg', 'jpeg', 'png', 'bmp'].every(item => !imgData?.path?.endsWith(item))) {
          wx.showToast({
            icon: 'none',
            title: '仅支持jpg、png、bmp类型的图片',
          })
          return
        }
        if ((+imgData?.size / 1024 / 1024) > 8) {
          wx.showToast({
            icon: 'none',
            title: '仅支持小于8M的图片',
          })
          return
        }
        uploadAliyun(
          img.tempFilePaths[0],
          (picPath) => {
            if (picPath) {
              this.recommend.clearSelect()
              this.setData({
                picPath
              })
            }
          },
          { directory: 'kejian-space/' }
        )
      },
    })
  },
  // 改变名称
  nameChange: function (e) {
    this.setData({
      name: e.detail.value
    })
  },
  // 改变备注
  remarkChange: function (e) {
    this.setData({
      remark: e.detail.value
    })
  },
  // 改变空间
  spaceChange: function (e) {
    this.setData({
      spaceSelect: this.data.spaceList[e.detail.value]
    })
  },
  // 保存
  async save() {
    if (this.loading) return
    this.loading = true
    const {
      name,
      remark,
      voicePath,
      voiceTime,
      picPath,
      defaultPicPath,
      spaceSelect,
      isSpace,
      isEdit
    } = this.data
    if (!name) {
      wx.showToast({
        icon: 'none',
        title: '名称不能为空',
      })
      this.loading = false
      return
    }
    if (name && !name.trim().length) {
      wx.showToast({
        icon: 'none',
        title: '名称不符合规范',
      })
      this.loading = false
      return
    }
    if (!isSpace && !spaceSelect) {
      wx.showToast({
        icon: 'none',
        title: '空间不能为空',
      })
      this.loading = false
      return
    }
    console.log('voiceTime', voiceTime);
    const res = await request.post(
      isEdit
        ? (isSpace ? api.spaceUpdate : api.containerUpdate)
        : (isSpace ? api.spaceAdd : api.containerAdd),
      {
        remarkText: remark,
        remarkVoice: voicePath,
        voiceLength: voiceTime,
        picUrl: picPath || defaultPicPath,
        ...(isEdit ? { id: this.id } : {}),
        ...(isSpace
          ? { spaceName: name }
          : { containerName: name, spaceId: spaceSelect?.id }
        ),
      }
    )
    if (res?.httpStatus === 200) {
      wx.showToast({
        icon: 'none',
        title: (isEdit ? '修改' : '添加') + '成功',
      })
      setTimeout(() => {
        wx.navigateBack({
          delta: 1,
        })
      }, 200)
    }
    this.loading = false
  },
  // 删除
  remove() {
    const { isSpace, hasChild } = this.data
    if (hasChild) {
      wx.showToast({
        icon: 'none',
        title: `请先将该${isSpace ? '房间' : '容器'}的${isSpace ? '容器' : '物品'}转移到其他位置`,
      })
    } else {
      this.removeModal.show()
    }
  },
  // 删除确认
  async removeConfirm() {
    if (this.loading) return
    this.loading = true
    this.removeModal.hide()

    const { isSpace } = this.data
    const res = await request.get(
      `${isSpace ? api.spaceRemove : api.containerRemove}/${this.id}`
    )
    if (res?.httpStatus === 200) {
      wx.showToast({
        icon: 'none',
        title: '删除成功',
      })
      setTimeout(() => {
        wx.navigateBack({
          delta: 2,
        })
      }, 200)
    }
    this.loading = false
  },
  // 用户点击右上角分享
  onShareAppMessage(e) {
    return shareOptions('default',e)
  },
})